//
//  Service.swift
//  接口配置文件
//  使用的是Moya网络框架+RxSwift
//  官网中文使用文档：https://github.com/Moya/Moya/blob/master/docs_CN/Examples/Basic.md
//
//  Created by smile on 2019/4/7.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

//网络请求框架
import Moya

// MARK: - 定义项目中所有接口
/// 定义项目中所有接口
///
/// - sheetDetail: 歌单详情
/// - sheets: 歌单列表
/// - createSheet: <#createSheet description#>
/// - addSongToSheet: <#addSongToSheet description#>
/// - deleteSongInSheet: <#deleteSongInSheet description#>
/// - createSheets: <#createSheets description#>
/// - collectSheets: <#collectSheets description#>
/// - ads: <#ads description#>
/// - userDetail: <#userDetail description#>
/// - updateUser: <#updateUser description#>
/// - songDetail: <#songDetail description#>
/// - friends: <#friends description#>
/// - follow: <#follow description#>
/// - deleteFollow: <#deleteFollow description#>
/// - collect: <#collect description#>
/// - deleteCollect: <#deleteCollect description#>
/// - fans: <#fans description#>
/// - songs: <#songs description#>
/// - videos: <#videos description#>
/// - videoDetail: <#videoDetail description#>
/// - comments: <#comments description#>
/// - searcheSuggests: <#searcheSuggests description#>
/// - searcheSheets: <#searcheSheets description#>
/// - searcheUsers: <#searcheUsers description#>
/// - createUser: <#createUser description#>
/// - login: <#login description#>
/// - resetPassword: <#resetPassword description#>
/// - sendSMSCode: <#sendSMSCode description#>
/// - sendEmailCode: <#sendEmailCode description#>
/// - like: <#like description#>
/// - deleteLike: <#deleteLike description#>
/// - createComment: <#createComment description#>
/// - createFeed: <#createFeed description#>
/// - topics: <#topics description#>
/// - feeds: <#feeds description#>
/// - shops: <#shops description#>
/// - shopDetail: <#shopDetail description#>
/// - orders: <#orders description#>
/// - orderDetail: <#orderDetail description#>
/// - createOrder: <#createOrder description#>
/// - ordersV2: <#ordersV2 description#>
/// - ordersV3: <#ordersV3 description#>
/// - createOrderV2: <#createOrderV2 description#>
/// - createOrderV3: <#createOrderV3 description#>
/// - orderPay: <#orderPay description#>
enum Service{
    case sheetDetail(id:String)
    case sheets
    case createSheet(title:String)
    case addSongToSheet(id:String,song_id:String)
    case deleteSongInSheet(id:String,song_id:String)
    case createSheets(id:String)
    case collectSheets(id:String)
    
    case ads
    
    //获取用户详情
    case userDetail(id:String,nickname:String?)
    case updateUser(id:String,nickname:String?,avatar:String?,desc:String?,gender:Int?,birthday:String?,province:String?,province_code:String?,city:String?,city_code:String?,area:String?,area_code:String?)
    
    case bindAccount(account:String,platform:Int)
    case unbindAccount(platform:Int)
    
    //歌曲详情
    case songDetail(id:String)
    
    //我的好友（我关注的人）
    case friends(id:String)
    
    //关注用户
    case follow(id:String)
    
    //取消关注用户
    case deleteFollow(id:String)
    
    case collect(id:String)
    case deleteCollect(id:String)
    
    //我的粉丝（关注我的人）
    case fans(id:String)
    
    //获取歌单列表
    case songs
    
    case videos
    case videoDetail(id:String)
    
    //获取评论列表
    case comments(sheet_id:String?,order:Int,page:Int)
    
    case searcheSuggests(query:String)
    case searcheSheets(query:String)
    case searcheUsers(query:String)
    
    case createUser(avatar:String?,nickname:String,phone:String,email:String,password:String,qq_id:String?,weibo_id:String?)
    case login(phone:String?,email:String?,password:String?,qq_id:String?,weibo_id:String?)
    case resetPassword(phone:String?,email:String?,code:String,password:String)
    
    case sendSMSCode(phone:String)
    case sendEmailCode(email:String)
    
    case like(comment_id:String)
    case deleteLike(id:String)
    
    case createComment(content:String,sheet_id:String?,parent_id:String?)
    
    case createFeed(content:String,province:String?,city:String?,longitude:Double?,latitude:Double?,images:[Dictionary<String,String>]?)
    
    case topics
    case feeds
    
    case shops
    case shopDetail(id:String)
    
    case orders
    case orderDetail(id:String)
    case createOrder(book_id:String,source:Int)
    
    //获取订单列表V2（响应签名）
    case ordersV2
    
    //获取订单列表V3（响应加密）
    case ordersV3
    
    //创建订单V2（参数签名）
    case createOrderV2(book_id:String,source:Int)
    
    //创建订单V3（参数加密）
    case createOrderV3(book_id:String,source:Int)
    
    case orderPay(id:String,channel:Int,origin:Int)
}


// MARK: - 实现TargetType协议
// 可以直接写，也可以用扩展
// 扩展写的好处是
extension Service: TargetType {
    
    /// 返回网址URL
    var baseURL: URL {
        return URL(string: ENDPOINT)!
    }
    
    /// 返回每个请求的路径
    var path: String {
        switch self {
        case .sheets, .createSheets:
            return "/v1/sheets.json"
        case .sheetDetail(let id):
            return "/v1/sheets/\(id).json"
        case .addSongToSheet(let id,let song_id):
            return "/v1/sheets/\(id)/relations.json"
        case .deleteSongInSheet(let id,let song_id):
            return "/v1/sheets/\(id)/relations/\(song_id)"
        case .createSheets(let id):
            return "/v1/users/\(id)/create.json"
        case .collectSheets(let id):
            return "/v1/users/\(id)/collect.json"
            
        case .ads:
            return "/v1/ads.json"
            
        case .userDetail(let id,let nickname):
            return "/v1/users/\(id).json"
            
        case .updateUser(let id, let nickname,let  avatar, let desc, let gender, let birthday, let province, let province_code, let city,let city_code, let area, let area_code):
            return "/v1/users/\(id).json"
            
        case .bindAccount:
            return "/v1/users/bind.json"
        case .unbindAccount(let platform):
            return "/v1/users/\(platform)/unbind.json"
            
        case .follow(let _):
            return "/v1/friends"
        case .deleteFollow(let id):
            return "/v1/friends/\(id).json"
            
        case .songDetail(let id):
            return "/v1/songs/\(id).json"
            
        case .collect(let _):
            return "/v1/collections.json"
        case .deleteCollect(let id):
            return "/v1/collections/\(id).json"
            
        case .friends(let id):
            return "/v1/users/\(id)/following"
        case .fans(let id):
            return "/v1/users/\(id)/followers"
            
        case .songs:
            return "/v1/songs.json"
        case .comments:
            return "/v1/comments.json"
            
        case .createOrder, .orders:
            return "/v1/orders.json"
            
        case .ordersV2, .createOrderV2:
            return "/v2/orders.json"
            
        case .ordersV3, .createOrderV3:
            return "/v3/orders.json"
            
        case .searcheSuggests:
            return "v1/searches/suggests"
        case .searcheSheets:
            return "v1/searches/sheets"
        case .searcheUsers(let query):
            return "v1/searches/users"
            
        case .createUser(_, _, _, _, _, _, _):
            return "/v1/users.json"
        case .login( _, _, _, _, _):
            return "/v1/sessions.json"
        case .resetPassword:
            return "/v1/users/reset_password"
            
        case .sendSMSCode:
            return "/v1/codes/request_sms_code"
        case .sendEmailCode:
            return "/v1/codes/request_email_code"
            
        case .videos:
            return "/v1/videos.json"
        case .videoDetail(let id):
            return "/v1/videos/\(id).json"
            
        case .like(let _):
            return "/v1/likes.json"
        case .deleteLike(let id):
            return "/v1/likes/\(id).json"
            
        case .createComment:
            return "/v1/comments.json"
            
        case .createFeed:
            return "/v1/feeds.json"
            
        case .topics:
            return "/v1/topics.json"
        case .feeds:
            return "/v1/feeds.json"
            
        case .shops:
            return "/v1/books.json"
        case .shopDetail(let id):
            return "/v1/books/\(id).json"
            
        case .orders:
            return "/v1/orders.json"
        case .orderDetail(let id):
            return "/v1/orders/\(id).json"
        case .orderPay(let id, let channel,let  origin):
            return "/v1/orders/\(id)/pay.json"
            
        default:
            return ""
        }
    }

    /// 返回每个请求的请求方式
    var method: Moya.Method {
        switch self {
        case .createUser, .login, .createOrder, .orderPay, .createOrderV2, .createOrderV3, .follow, .collect, .resetPassword, .sendSMSCode, .sendEmailCode, .like, .createComment, .createFeed, .createSheet, .bindAccount:
            
            //创建内容
            return .post
            
        case .deleteFollow, .deleteCollect, .deleteLike, .deleteSongInSheet, .unbindAccount:
            
            //删除资源
            return .delete
            
        case .updateUser:
            
            //更新
            return .patch
            
        default:
            return .get
        }
    }
    
    /// 这是测试相关的
    /// 这里用不到
    var sampleData: Data {
        return Data()
    }
    
    /// 返回每个请求的参数
    var task: Task {
        switch self {
        //创建用户请求
        case .createUser(let avatar, let nickname,let phone, let email, let password, let qq_id, let weibo_id):
            return .requestParameters(parameters: ["avatar":avatar,"nickname": nickname, "phone": phone,"email":email,"password":password,"qq_id":qq_id,"weibo_id":weibo_id], encoding: JSONEncoding.default)
            
        //登陆
        case .login(let phone, let email, let password, let qq_id, let weibo_id):
            return .requestParameters(parameters: ["phone": phone,"email":email,"password":password,"qq_id":qq_id,"weibo_id":weibo_id], encoding: JSONEncoding.default)
        case .resetPassword(let phone, let email, let code, let password):
            return .requestParameters(parameters: ["phone": phone,"email":email,"code":code,"password":password], encoding: JSONEncoding.default)
            
        case .userDetail(let id, let nickname):
            return .requestParameters(parameters: ["nickname": nickname ?? ""], encoding: URLEncoding.default)
            
        case .bindAccount(let account, let platform):
            return .requestParameters(parameters: ["account": account,"platform":platform], encoding: JSONEncoding.default)
        
        case .sendSMSCode(let phone):
            return .requestParameters(parameters: ["phone": phone], encoding: JSONEncoding.default)
        case .sendEmailCode(let email):
            return .requestParameters(parameters: ["email": email], encoding: JSONEncoding.default)
            
        case .orderPay(let id, let channel, let origin):
            return .requestParameters(parameters: ["channel": channel,"origin":origin], encoding: JSONEncoding.default)
            
        case .createOrder(let book_id, let source), .createOrderV2(let book_id, let source), .createOrderV3(let book_id, let source):
            return .requestParameters(parameters: ["book_id": book_id,"source":source], encoding: JSONEncoding.default)
            
        //获取搜索建议
        case .searcheSuggests(let query):
            //GET方式传递参数
            //要用URLEncoding编码
            //不能用JSONEncoding
            return .requestParameters(parameters: ["query": query], encoding: URLEncoding.default)
            
        //歌单搜索
        case .searcheSheets(let query):
            return .requestParameters(parameters: ["query": query], encoding: URLEncoding.default)
            
        //歌单搜索
        case .searcheUsers(let query):
            return .requestParameters(parameters: ["query": query], encoding: URLEncoding.default)
            
        case .like(let comment_id):
            return .requestParameters(parameters: ["comment_id": comment_id], encoding: JSONEncoding.default)
            
            //收藏歌单
        case .collect(let id):
            return .requestParameters(parameters: ["sheet_id": id], encoding: JSONEncoding.default)
            
        case .createComment(let content, let  sheet_id, let  parent_id):
            return .requestParameters(parameters: ["content":content,"sheet_id": sheet_id, "parent_id": parent_id], encoding: JSONEncoding.default)
            
        case .createFeed(let content, let  province, let  city, let longitude, let latitude, let images):
            return .requestParameters(parameters: ["content":content,"province": province, "city": city, "longitude":longitude, "latitude":latitude, "images":images], encoding: JSONEncoding.default)
            
        case .createSheet(let title):
            return .requestParameters(parameters: ["title":title], encoding: JSONEncoding.default)
            
        case .addSongToSheet(let id, let song_id):
            return .requestParameters(parameters: ["id":song_id], encoding: JSONEncoding.default)
            
        case .updateUser(let id, let nickname,let  avatar, let desc, let gender, let birthday, let province, let province_code, let city,let city_code, let area, let area_code):
            
            //判断参数
            //如果为空
            //服务端现在的实现是清除该字段
            //所以要判断
            var params:[String:Any]=[:]
            
            if let nickname = nickname {
                params["nickname"]=nickname
            }
            
            if let avatar = avatar {
                params["avatar"]=avatar
            }
            
            if let gender = gender {
                params["gender"]=gender
            }
            
            if let birthday = birthday {
                params["birthday"]=birthday
            }
            
            if let desc = desc {
                params["description"]=desc
            }
            
            if let province = province {
                params["province"]=province
            }
            
            if let province_code = province_code {
                params["province_code"]=province_code
            }
            
            if let city = city {
                params["city"]=city
            }
            
            if let city_code = city_code {
                params["city_code"]=city_code
            }
            
            if let area = area {
                params["area"]=area
            }
            
            if let area_code = area_code {
                params["area_code"]=area_code
            }
            
            //将参数编码为JSON
            return .requestParameters(parameters: params, encoding: JSONEncoding.default)
            
        default:
            //不传递参数
            return .requestPlain
        }
    }
    
    /// 请求头
    var headers: [String : String]? {
        
        var headers:Dictionary<String,String>=[:]
        
        //内容类型
        headers["Content-Type"]="application/json"
        
        //判断是否登陆了
        if PreferenceUtil.isLogin() {
            //打印token
            //是为了方便调试
            //打包要去除
            if DEBUG {
                print("user:\(PreferenceUtil.userId()!) token:\(PreferenceUtil.userToken())")
            }
            
            //登陆了传递请求头
            //在请求头中添加，User和Authorization
            headers["User"]=PreferenceUtil.userId()
            headers["Authorization"]=PreferenceUtil.userToken()
        }
        
        return headers
    }
}

